﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using Citi.CheckShare.SchedulerUi.EmailSenderWcf;
using Citi.Helpers;
using Citi.RoutineBase;
using System.Diagnostics;
using Microsoft.Storage;

namespace Citi.CheckShare.SchedulerUi
{
    public class CheckShares : IExecutableRoutine
    {
        private readonly string xmlPath = ConfigurationManager.AppSettings["XmlPath"];

        public IEnumerable<RoutineParameter> Parameters
        {
            get { return null; }
        }

        public void Rollback(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }

        public void Start(DateTime scheduledDate, ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            var shares = new List<ShareData>();

            var robotUsername = parameters["RobotUsername"].ToString();
            var robotPassword = parameters["RobotPassword"].ToString();

            currentAction.Description = "Getting shares to check";
            using (SecurityHelper.ImpersonateCitiUser.GetImpersonateUser("lac_bra_ftools", robotUsername, robotPassword))
            {
                shares = XmlHelper.DeserializeFromXml<List<ShareData>>(xmlPath);
            }

            currentAction.Description = string.Format("Was found {0} shares", shares.Count);

            foreach (var share in shares)
            {
                currentAction.Description = string.Format("Checking share '{0}' using creditials: {1}", share.Path, share.SoeidExecuteAs);

                using (SecurityHelper.ImpersonateCitiUser.GetImpersonateUser(share.SoeidExecuteAs, robotUsername, robotPassword))
                {
                    var directoryInfo = new DirectoryInfo(share.Path);
                    currentAction.Description = "Getting share quota";
                    var totalSize = WindowsUtil.GetDirectorySize(share.Path, true) / 1048576;

                    var percentUsed = Convert.ToInt64(decimal.Divide(totalSize, share.SpaceMB) * 100);
                    var warningUsers = share.WarningUsers.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Distinct().ToList();
                    var criticalUsers = share.CriticalUsers.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    criticalUsers.AddRange(warningUsers);
                    criticalUsers = criticalUsers.Distinct().ToList();

                    var parametersEmail = FillParameters(share, percentUsed, totalSize);

                    if (percentUsed >= share.CriticalPercent)
                    {
                        currentAction.Description = "Critical use. Sending email";
                        SendEmailWithTemplate(criticalUsers, null, null, 1030, parametersEmail);
                    }
                    else if (percentUsed >= share.WarningPercent)
                    {
                        currentAction.Description = "Warning use. Sending email";
                        SendEmailWithTemplate(warningUsers, null, null, 1029, parametersEmail);
                    }
                }
            }
        }

        private Dictionary<string, string> FillParameters(ShareData share, long percentUsed, long currentSize)
        {
            return new Dictionary<string, string>
                {
                    { "[CriticalPercent]", share.CriticalPercent.ToString()},
                    { "[Path]", share.Path},
                    { "[Directory]", Path.GetFileName(share.Path)},
                    { "[SoeidExecuteAs]", share.SoeidExecuteAs},
                    { "[SpaceMB]", share.SpaceMB.ToString()},
                    { "[CurrentSize]", currentSize.ToString()},
                    { "[WarningPercent]",share.WarningPercent.ToString()},
                    { "[PercentUsed]", percentUsed.ToString()},
                };
        }

        private void SendEmailWithTemplate(List<string> to, List<string> cc, List<string> bcc, int templateId, Dictionary<string, string> parameters)
        {
            using (var client = new EmailClient())
            {
                to = to != null ? to.Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().ToList() : new List<string>();
                cc = cc != null ? cc.Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().ToList() : new List<string>();
                bcc = bcc != null ? bcc.Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().ToList() : new List<string>();

                var email = new Email
                {
                    TemplateId = templateId,
                    Importance = EnumsEmailImportance.Normal,
                    To = to.Select(x => new EmailAddress { Description = x }).ToList(),
                    Cc = cc.Select(x => new EmailAddress { Description = x }).ToList(),
                    Bcc = bcc.Select(x => new EmailAddress { Description = x }).ToList(),
                    Parameters = parameters
                };

                client.InsertEmailInQueue(email);
            }
        }

        public void Stop(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }
    }
}
